var Towxml = require('/assets/libs/towxml/main.js');
App({
  //请不要修改 /addons/cms/wxapp.这部分,只允许修改域名部分
  //请注意小程序只支持https  http://47.97.182.0:8088/KuaKua/api
  // http://localhost:8088/KuaKua/api
  apihost: 'https://childtest.sheshanshy.com/api/',
  si: 0,
  //小程序启动
  onLaunch: function () {
     
  },
  //投票
  vote: function (event, cb) {
    
  },
  //判断是否登录
  check: function (cb) {
    
  },
  //登录
  login: function (cb) {
    var that = this;
        //调用登录接口
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          console.log(res.code);
          wx.getUserInfo({
            success: function (ures) {
              console.log("users",ures);
              wx.request({
                url: that.apiUrl + '/saveUser',
                data: {
                  code: res.code,
                  rawData: ures.userInfo
                }, 
                header: {
                  'content-type': 'application/json'  
                },
                method: 'post', 
                success: function (lres) {
                  console.log("lres", lres);
                  var data = lres.data
                  if (data.code == 200) {
                    that.globalData.userInfo = data.data;
                    wx.setStorageSync('userInfo', data.data);
                    typeof cb == "function" && cb(that.globalData.userInfo);
                  } else {
                    wx.setStorageSync('token', '');
                    console.log("用户登录失败")
                    that.showLoginModal(cb);
                  }
                }
              });
            },
            fail: function (res) {
              that.showLoginModal(cb);
            }
          });
        } else {
          that.showLoginModal(cb);
        }
      }
    });
  },
  //显示登录或授权提示
  showLoginModal: function (cb) {
    var that = this;
    if (!that.globalData.userInfo) {
      //获取用户信息
      wx.getSetting({
        success: function (sres) {
          if (sres.authSetting['scope.userInfo']) {
            wx.showModal({
              title: '温馨提示',
              content: '当前无法获取到你的个人信息，部分操作可能受到限制',
              confirmText: "重新登录",
              cancelText: "暂不登录",
              success: function (res) {
                if (res.confirm) {
                  that.login(cb);
                } else {
                  console.log('用户暂不登录');
                }
              }
            });
          } else {
            wx.showModal({
              title: '温馨提示',
              content: '当前无法获取到你的个人信息，部分操作可能受到限制',
              confirmText: "去授权",
              cancelText: "暂不授权",
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/page/my/setting?type=getuserinfo',
                  });
                  return false;
                  wx.openSetting({
                    success: function (sres) {
                      that.check(cb);
                    }
                  });
                } else {
                  console.log('用户暂不授权');
                }
              }
            });
          }
        }
      });
    } else {
      typeof cb == "function" && cb(that.globalData.userInfo);
    }
  },
  //发起网络请求
  postrequest: function (url, data, success, error) {
    var that = this; 
    wx.request({
      url: that.apihost + url,
      data: data,
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        var code, msg, json;
        console.log(res);
        if (res.statusCode === 200) {
          json = res.data;
          if (json.code === 1) {
            typeof success === 'function' && success(json.data, json);
          } else {
            typeof error === 'function' && error(json.data, json);
          }
        } else {
          json = typeof res.data === 'object' ? res.data : { code: 0, msg: '发生一个未知错误', data: null };
          typeof error === 'function' && error(json.data, json);
        }
      },
      fail: function (res) {
        that.loading(false);
        console.log("fail:", res);
        typeof error === 'function' && error(null, { code: 0, msg: '', data: null });
      }
    });
  },
  /**
  * 网络请求封装
  */
  getData(url, data, method, mysuccess) {
    var that = this
    //that.checkSession() 
    wx.request({
      url: that.apiUrl + url,
      data: data,
      method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log("res",res);
        if (res.data.code == 200) {
          mysuccess(res);
        }else{
          console.log("请求数据出错了");
        }
        
      },
      fail: function (res) {
        // fail(res);
        console.log(res);
      },
      complete: function (res) {
        //complete(res);
      }
    })

  },
  //构造CDN地址
  cdnurl:function(url){
    return url.toString().match(/^https?:\/\/(.*)/i) ? url : this.globalData.config.upload.cdnurl + url;
  },
  //文本提示
  info: function (msg, cb) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000,
      complete: function () {
        typeof cb == "function" && cb();
      }
    });
  },
  //成功提示
  success: function (msg, cb) {
    wx.showToast({
      title: msg,
      icon: 'success', 
      duration: 2000,
      complete: function () {
        typeof cb == "function" && cb();
      }
    });
  },
  //错误提示
  error: function (msg, cb) {
    wx.showToast({
      title: msg,
      image: '/assets/images/error.png',
      duration: 2000,
      complete: function () {
        typeof cb == "function" && cb();
      }
    });
  },
  //警告提示
  warning: function (msg, cb) {
    wx.showToast({
      title: msg,
      image: '/assets/images/warning.png',
      duration: 2000,
      complete: function () {
        typeof cb == "function" && cb();
      }
    });
  },
  //Loading
  loading: function (msg) {
    if (typeof msg == 'boolean') {
      if (!msg) {
        if (!this.si) {
          return;
        }
        clearTimeout(this.si);
        wx.hideLoading({});
        return;
      }
    }
    msg = typeof msg == 'undefined' || typeof msg == 'boolean' ? '加载中' : msg;
    this.globalData.loading = true;
    if (this.si) {
      return;
    }
    this.si = setTimeout(function () {
      wx.showLoading({
        title: msg
      });
    }, 300);

  },
  towxml: new Towxml(),
  //全局信息
  globalData: {
    userInfo: null,
    config: null,
    indexTabList: [],
    newsTabList: [],
    productTabList: [],
  }
})
